package com.google.code.gwtmvpscaffold;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Utils {

  public static String readFileToString(String filePath) {
    InputStream is;
    try {
      is = new FileInputStream(filePath);
      Writer writer = new StringWriter();

      char[] buffer = new char[1024];
      try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
          return null;
        }
      }
      return writer.toString();
    } catch (FileNotFoundException e1) {
      e1.printStackTrace();
    }
    return null;
  }

  public static String readFromResouce(String file) {
    try {
      InputStream is = Class.class.getResourceAsStream("/" + file);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

      Writer writer = new StringWriter();

      char[] buffer = new char[1024];
      try {
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
          return null;
        }
      }
      return writer.toString();

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return null;
  }

  public static boolean writeToFile(String content, String path) {
    try {
      // Create file
      createParentDirectories(path);
      FileWriter fstream = new FileWriter(path);
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(content);
      // Close the output stream
      out.close();
    } catch (Exception e) {// Catch exception if any
      System.err.println("Error: " + e.getMessage());
      return false;
    }

    return true;
  }

  public static void createParentDirectories(String path) {
    final File file = new File(path);
    final File parent_directory = file.getParentFile();

    if (null != parent_directory) {
      parent_directory.mkdirs();
    }
  }

  public static void createDirectory(String path) {
    final File file = new File(path);
    file.mkdirs();
  }

  public static void zipDir(String zipFileName, String dir) throws Exception {
    File dirObj = new File(dir);
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
    System.out.println("Creating : " + zipFileName);
    addDir(dirObj, out, dir);
    out.close();
  }

  private static void addDir(File dirObj, ZipOutputStream out, String firstDir) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
      if (files[i].isDirectory()) {
        addDir(files[i], out, firstDir);
        continue;
      }
      FileInputStream in = new FileInputStream(files[i].getAbsolutePath());

      String zipEntryPath = files[i].getAbsolutePath().substring(firstDir.length(),
          files[i].getAbsolutePath().length());

      String escapedSep = SystemVariables.SEP;
      if (SystemVariables.SEP.equals("\\"))
        escapedSep = "\\" + SystemVariables.SEP;

      if (zipEntryPath.startsWith(SystemVariables.SEP))
        zipEntryPath.replaceFirst(escapedSep, "");

      System.out.println(" Adding: " + zipEntryPath);

      out.putNextEntry(new ZipEntry(zipEntryPath));
      int len;
      while ((len = in.read(tmpBuf)) > 0) {
        out.write(tmpBuf, 0, len);
      }
      out.closeEntry();
      in.close();
    }
  }

  public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        boolean success = deleteDir(new File(dir, children[i]));
        if (!success) {
          return false;
        }
      }
    }

    // The directory is now empty so delete it
    return dir.delete();
  }

}
